"""
Miscellaneous utility functions used by this module.

"""

# messing with dictionaries

def merge(*dicts):
    r = {}
    for d in dicts:
        r.update(d)
    return r

def mget(d, keys, default=None):
    for key in keys:
        if key in d:
            return d[key]
    else:
        return default

# apparently python 2.5 already has these two functions
def any(g):
    for e in g:
        if e:
            return True
    else:
        return False

def all(g):
    for e in g:
        if not e:
            return False
    else:
        return True

# time/date stuff

import time
def to_timestamp(t):
    """
    See if `t` can be converted to a timestamp as if it were a datetime object,
    if not, just return the string version of `t`, assuming it is already a
    timestamp.
    
    """
    try:
        return str(int(time.mktime(t.timetuple())))
    except AttributeError:
        return str(t)

def to_date(t):
    return str(t)

def to_ymd(t):
    return str(t)[:10]

import datetime
def from_timestamp(timestamp):
    """
    Convert a UNIX `timestamp`, such as '1175210261' into a datetime object.

    """
    return datetime.datetime.fromtimestamp(float(timestamp))

def from_date(datestring):
    """
    Convert a variety of date strings, such as '2007-02-01 23:02:01', into
    datetime objects.

    """
    def convert(s, format):
        return datetime.datetime(*(time.strptime(s, format)[0:6]))

    # The Flickr API spec calls these different formats 'granularities'
    formats = [
        '%Y-%m-%d %H:%M:%S',
        '%Y-%m',
        '%Y',
    ]                                                                                                                                        

    for format in formats:
        try:
            return convert(datestring, format)
        except ValueError:
            continue
    if datestring == '0000-00-00 00:00:00':
        return None 
    raise GlittrError, "Could not parse date string: %s" % x
